//
//  UserAccount.swift
//  微博
//
//  Created by 吴思达 on 16/3/10.
//  Copyright © 2016年 吴思达. All rights reserved.
//

import UIKit
import AFNetworking

private let userInforKey = "cn.itcast.account"
class UserAccount: NSObject {
    
    static let shareAccount = UserAccount()
    
    var access_token: String?
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var expires_date : NSDate?
    var uid: String?
    var name: String?
    var avatar_large: String?
    var userLogin: Bool{
        return access_token != nil
    }
    override init() {
        super.init()
        self.loadUserInfo()
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String)
    { }
    
    override var description: String {
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
        let accountDict = dictionaryWithValuesForKeys(keys)
        
        return accountDict.description
    }
}

extension UserAccount {
    
    func loadAccessToken(code: String, finished: (isSucess: Bool) -> () ) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let paraments = ["client_id" : client_id, "client_secret" : client_secret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" : redirect_uri]
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        AFN.POST(urlString, parameters: paraments, progress: nil
            , success: { (_, result) -> Void in
                print(result)
                print(result?.classForCoder)
                
                guard let dict = result as? [String : AnyObject] else {
                    finished(isSucess: false)
                    return
                }
                self.loadUserInfor(dict, finished: finished)
                
            }) { (_, error) -> Void in
                finished(isSucess: false)
                print(error)
        }
        
    }
    
    private func loadUserInfor(dict : [String : AnyObject], finished: (isSucess: Bool) -> ()) {
        let token = dict["access_token"] as! String
        let uid = dict["uid"] as! String
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token": token, "uid": uid]
        let AFN = AFHTTPSessionManager()
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            guard var userInforDict = result as? [String : AnyObject] else {
                finished(isSucess: false)
                return
            }
            for (k,v) in dict {
                userInforDict[k] = v
            }
            //保存到沙盒
            UserAccount.shareAccount.saveUserInfor(userInforDict)
            finished(isSucess: true)
            
            }) { (_, error) -> Void in
                print(error)
        }
    }
}
// 账户相关的业务逻辑的扩展
//保存数据,获取数据
extension UserAccount {
    
    func saveUserInfor(dict: [String : AnyObject]) {
        self.setValuesForKeysWithDictionary(dict)
        let userDefault = NSUserDefaults.standardUserDefaults()
        let keys = ["access_token","expires_in","uid","name","avatar_large"]
        let accountDict = self.dictionaryWithValuesForKeys(keys)
        userDefault.setObject(accountDict, forKey: userInforKey)
        userDefault.synchronize()
        print(NSHomeDirectory())
    }
    
    func loadUserInfo() {
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInforKey) as? [String : AnyObject] else {
            return
        }
        self.setValuesForKeysWithDictionary(dict)
        
        if self.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("token 正常")
        } else{
            print("token 过期")
            access_token = nil
        }
    }
}
